package zj.it.bhne.gridengineeringsurvey.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.entity.Equip;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.AngleUtil;
import zj.it.bhne.gridengineeringsurvey.myutils.MyUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;

import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.Distance;
import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.openDatabase;


public class DistanceActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "DistanceActivity";
    private Long aid, bid, cid;
    private Spinner dis_sp;
    private EditText dis_ed_deng;
    private RelativeLayout dis_rl_deng;
    private EditText dis_ed_ding;
    private RelativeLayout dis_rl_ding;
    private Context context;
    private LatLng latLng_a, latLng_b;
    private Spinner dis_sp_sort;
    private Spinner dis_sp_equ;
    private Double length;
    private Points points_a, points_b;
    private List<Equip> equipList = new ArrayList<>();
    private List<Points> pointsList = new ArrayList<>();
    private Spinner dis_sp_qsd;
    private RelativeLayout dis_rl_zi;

    /**
     * 已知两点经纬度求方位角
     */
    public static double getAngle(double lon1, double lat1, double lon2,
                                  double lat2) {
        double fLat = Math.PI * (lat1) / 180.0;
        double fLng = Math.PI * (lon1) / 180.0;
        double tLat = Math.PI * (lat2) / 180.0;
        double tLng = Math.PI * (lon2) / 180.0;

        double degree = (Math.atan2(Math.sin(tLng - fLng) * Math.cos(tLat), Math.cos(fLat) * Math.sin(tLat) - Math.sin(fLat) * Math.cos(tLat) * Math.cos(tLng - fLng))) * 180.0 / Math.PI;
        if (degree >= 0) {
            return degree;
        } else {
            return 360 + degree;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_distance);
        context = this;
        initView();
        Intent intent = getIntent();
        aid = intent.getLongExtra("aid", 0);
        bid = intent.getLongExtra("bid", 0);
        cid = intent.getLongExtra("cid", 0);
        length = intent.getDoubleExtra("length", 0);
        initData();
    }

    private void initData() {

        points_a = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(aid)).build().list().get(0);
        points_b = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(bid)).build().list().get(0);
        latLng_a = new LatLng(Double.valueOf(points_a.getLat()), Double.valueOf(points_a.getLon()));
        latLng_b = new LatLng(Double.valueOf(points_b.getLat()), Double.valueOf(points_b.getLon()));

        //Log.e(TAG, "addInitMap: " + points_b.getMark());

        List<String> adapter_dataq = new ArrayList<>();
        adapter_dataq.add(points_a.getMark());
        adapter_dataq.add(points_b.getMark());
        //适配器
        ArrayAdapter<String> arr_adapterq = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_dataq);
        //设置样式
        arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dis_sp_qsd.setAdapter(arr_adapterq);
    }

    public List<Equip> getGuPiaoDaiMA(int str) {
        List<Equip> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Equip equip = new Equip();
            equip.setId(cursor.getInt(0));
            equip.setName(cursor.getString(1));
            equip.setCode(cursor.getString(4));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }


    private void initView() {
        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        TextView activity_tv_save = findViewById(R.id.activity_tv_save);
        dis_sp = findViewById(R.id.dis_sp);
        dis_ed_deng = findViewById(R.id.dis_ed_deng);
        dis_rl_deng = findViewById(R.id.dis_rl_deng);
        dis_ed_ding = findViewById(R.id.dis_ed_ding);
        dis_rl_ding = findViewById(R.id.dis_rl_ding);
        Button dis_btn_save = findViewById(R.id.dis_btn_save);
        dis_sp_sort = findViewById(R.id.dis_sp_sort);
        dis_sp_equ = findViewById(R.id.dis_sp_equ);
        dis_btn_save.setOnClickListener(this);
        activity_tv_save.setOnClickListener(this);
        activity_ib_back.setOnClickListener(this);
        activity_tv_title.setText("插入杆塔");
        activity_tv_save.setText("取消");

        dis_sp_qsd = findViewById(R.id.dis_sp_qsd);
        dis_rl_zi = findViewById(R.id.dis_rl_zi);

        dis_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        dis_rl_deng.setVisibility(View.VISIBLE);
                        dis_rl_ding.setVisibility(View.GONE);
                        break;
                    case 1:
                        dis_rl_deng.setVisibility(View.GONE);
                        dis_rl_ding.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        dis_rl_deng.setVisibility(View.GONE);
                        dis_rl_ding.setVisibility(View.VISIBLE);
                        dis_rl_zi.setVisibility(View.VISIBLE);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dis_sp_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    final List<Equip> equip = getGuPiaoDaiMA(1);
                    List<String> adapter_data1 = new ArrayList<>();
                    for (int i = 0; i < equip.size(); i++) {
                        adapter_data1.add(equip.get(i).getName());
                        equipList.add(equip.get(i));
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter1 = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_data1);
                    //设置样式
                    arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    dis_sp_equ.setAdapter(arr_adapter1);
                } else if (position == 1) {
                    final List<Equip> equip2 = getGuPiaoDaiMA(2);
                    List<String> adapter_data3 = new ArrayList<>();
                    for (int i = 0; i < equip2.size(); i++) {
                        adapter_data3.add(equip2.get(i).getName());
                        equipList.add(equip2.get(i));
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter3 = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_data3);
                    //设置样式
                    arr_adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    dis_sp_equ.setAdapter(arr_adapter3);
                } else {
                    final List<Equip> equips = getGuPiaoDaiMA(4);
                    List<String> adapter_dataq = new ArrayList<>();
                    for (int i = 0; i < equips.size(); i++) {
                        adapter_dataq.add(equips.get(i).getName());
                        equipList.add(equips.get(i));
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapterq = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_dataq);
                    //设置样式
                    arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    dis_sp_equ.setAdapter(arr_adapterq);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_ib_back:
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.activity_tv_save:
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.dis_btn_save:
                save();
                //delete();
                break;
        }
    }

    /**
     * 点击踩点时进行的操作
     */
    private void save() {
        points_b.setGlsb("");
        MyApplication.getInstances().getPointsDao().update(points_b);
        if ("等距".equals(dis_sp.getSelectedItem().toString().trim())) {
            int number = Integer.parseInt(dis_ed_deng.getText().toString().trim());
            Long add;
            if (number > 20) {
                MyUtils.getToast(context, "一次性踩点过多");
            } else {
                List<LatLng> lng = getDengLatLng(number);

                add = addInitMap(lng, dis_sp_sort.getSelectedItem().toString().trim(), 1);

                if (add > 0) {
                    MyUtils.getToast(context, "踩点成功");
                    startActivity(new Intent(context, MapActivity.class));
                }
            }
        } else if ("自由".equals(dis_sp.getSelectedItem().toString().trim())) {
            Long add;
            int number = Integer.parseInt(dis_ed_ding.getText().toString().trim());
            List<LatLng> latLngList;
            //Log.e(TAG, "save: " + dis_sp_qsd.getSelectedItemId());
            if (dis_sp_qsd.getSelectedItemId() == 0) {
                latLngList = getZiYouLatLng(number, "0");
            } else {
                latLngList = getZiYouLatLng(number, "1");
            }
            add = addInitMap(latLngList, dis_sp_sort.getSelectedItem().toString().trim(), 2);
            if (add > 0) {
                MyUtils.getToast(context, "踩点成功");
                startActivity(new Intent(context, MapActivity.class));
            }
        } else {
            int number = Integer.parseInt(dis_ed_ding.getText().toString().trim());
            Long add;
            if (number > length && number < 5) {
                MyUtils.getToast(context, "定的点距太大或太小");
            } else {
                List<LatLng> latLngList = getDingLatLng(number);
                add = addInitMap(latLngList, dis_sp_sort.getSelectedItem().toString().trim(), 3);
                if (add > 0) {
                    MyUtils.getToast(context, "踩点成功");
                    startActivity(new Intent(context, MapActivity.class));
                }
            }
        }
    }

    /**
     * 实现自由选点
     *
     * @param number 距离
     * @return 经纬度
     */
    private List<LatLng> getZiYouLatLng(int number, String name) {
        List<LatLng> latLngList = new ArrayList<>();
        if (name.equals("0")) {
            double degree = getAngle(latLng_a.longitude, latLng_a.latitude, latLng_b.longitude, latLng_b.latitude);
            AngleUtil angleUtil = new AngleUtil(latLng_a.longitude, latLng_a.latitude);
            latLngList.add(AngleUtil.getMyLatLng(angleUtil, number, degree));
        } else {
            double degree = getAngle(latLng_b.longitude, latLng_b.latitude, latLng_a.longitude, latLng_a.latitude);
            AngleUtil angleUtil = new AngleUtil(latLng_a.longitude, latLng_a.latitude);
            latLngList.add(AngleUtil.getMyLatLng(angleUtil, number, degree));
        }
        return latLngList;
    }

    /**
     * 计算两点之间定距的经纬度
     */
    private List<LatLng> getDingLatLng(int number) {
        int num = (int) (length / number);
        List<LatLng> latLngList = new ArrayList<>();
        double degree = getAngle(latLng_a.longitude, latLng_a.latitude, latLng_b.longitude, latLng_b.latitude);
        AngleUtil angleUtil = new AngleUtil(latLng_a.longitude, latLng_a.latitude);
        for (int j = 1; j < num + 1; j++) {
            latLngList.add(AngleUtil.getMyLatLng(angleUtil, number * j, degree));
        }
        return latLngList;
    }


    /**
     * 计算两点之间等距的经纬度
     */
    private List<LatLng> getDengLatLng(int number) {
        double aaa, bbb, ccc = 0, ddd = 0;
        List<LatLng> latLngs = new ArrayList<>();
        for (int i = 1; i < number + 1; i++) {
            if (latLng_a.longitude > latLng_b.longitude && latLng_a.latitude > latLng_b.latitude) {
                aaa = (latLng_a.longitude - latLng_b.longitude) / (number + 1);
                ccc = latLng_b.longitude + aaa * (i);
                bbb = (latLng_a.latitude - latLng_b.latitude) / (number + 1);
                ddd = bbb * (i) + latLng_b.latitude;

            } else if (latLng_a.longitude < latLng_b.longitude && latLng_a.latitude < latLng_b.latitude) {
                aaa = (latLng_b.longitude - latLng_a.longitude) / (number + 1);
                ccc = latLng_a.longitude + aaa * (i);
                bbb = (latLng_b.latitude - latLng_a.latitude) / (number + 1);
                ddd = latLng_a.latitude + bbb * i;

            } else if (latLng_a.longitude > latLng_b.longitude && latLng_a.latitude < latLng_b.latitude) {
                aaa = (latLng_a.longitude - latLng_b.longitude) / (number + 1);
                ccc = latLng_b.longitude + aaa * (number + 1 - i);
                bbb = (latLng_b.latitude - latLng_a.latitude) / (number + 1);
                ddd = latLng_a.latitude + bbb * i;

            } else if (latLng_a.longitude < latLng_b.longitude && latLng_a.latitude > latLng_b.latitude) {
                aaa = (latLng_b.longitude - latLng_a.longitude) / (number + 1);
                ccc = latLng_a.longitude + aaa * (i);
                bbb = (latLng_a.latitude - latLng_b.latitude) / (number + 1);
                ddd = latLng_a.latitude - bbb * i;

            }

            latLngs.add(new LatLng(ddd, ccc));
        }
        return latLngs;
    }


    /**
     * 增加marker点
     */
    private Long addInitMap(List<LatLng> latLng, String name, int num) {

        Long number = null;


        if (num == 2) {
            for (int i = 0; i < latLng.size(); i++) {
                number = addMarker(latLng, i, name);
            }
            pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
            points_a.setGlsb(pointsList.get(pointsList.size() - 1).getMark());
            MyApplication.getInstances().getPointsDao().update(points_a);
        } else {
            for (int i = latLng.size() - 1; i > -1; i--) {
                number = addMarker(latLng, i, name);
            }
            pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
            points_a.setGlsb(pointsList.get(pointsList.size() - 1).getMark());
            MyApplication.getInstances().getPointsDao().update(points_a);
        }
        return number;

    }

    /**
     * @param latLng 经纬度集合
     * @param i      下标
     * @param name   名称
     */
    private Long addMarker(List<LatLng> latLng, int i, String name) {
        double lengths;
        Points points = new Points();
        points.setId(null);
        UUID uuid = UUID.randomUUID();
        points.setUid(uuid + "");
        points.setItems_id(cid);
        points.setNote("备注信息：");
        points.setLat(latLng.get(i).latitude + "");
        points.setLon(latLng.get(i).longitude + "");
        points.setHigh("");
        points.setBatch("1");
        points.setSblx(dis_sp_equ.getSelectedItem().toString().trim());
        List<Points> pointsList1 = MyApplication.getInstances().getPointsDao().queryBuilder().build().list();

        for (int j = 0; j < equipList.size(); j++) {
            Long mid = pointsList1.get(pointsList1.size() - 1).getId() + 1;
            points.setMark(equipList.get(j).getCode() + "-" + mid);

        }

        points.setName(name);
        points.setSbbh(dis_sp_equ.getSelectedItem().toString().trim());
        points.setOld("新建");

        if (name.equals("地形点")) {
            points.setGlsb("");
            points.setWhether("1");
            points.setCategory("条状物");
        } else {


            points.setWhether("0");

            final List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid), PointsDao.Properties.Whether.eq("0")).build().list();

            if (pointsList.size() > 0) {
                //Log.e(TAG, "addInitMap: " + pointsList.get(pointsList.size() - 1).getMark());

                points.setGlsb(pointsList.get(pointsList.size() - 1).getMark());
                BigDecimal bg = new BigDecimal(Distance(Double.valueOf(latLng.get(i).latitude + ""), Double.valueOf(latLng.get(i).longitude + ""), Double.valueOf(pointsList.get(pointsList.size() - 1).getLat()), Double.valueOf(pointsList.get(pointsList.size() - 1).getLon()))).setScale(2, RoundingMode.UP);
                lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                Points pointsL = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Mark.eq(points.getGlsb())).build().list().get(0);
                List<Line> lineList = MyApplication.getInstances().getLineDao().queryBuilder().build().list();
                Line line = new Line();
                line.setId(null);
                line.setItem_id(cid);
                line.setLatA(latLng.get(i).latitude + "");
                line.setLonA(latLng.get(i).longitude + "");
                line.setLatB(pointsList.get(pointsList.size() - 1).getLat());
                line.setLonB(pointsList.get(pointsList.size() - 1).getLon());
                line.setStart_id(points.getUid());
                line.setEnd_id(pointsL.getUid());
                line.setLength(lengths + "");
                if (pointsList.get(pointsList.size() - 1).getName().equals("杆塔") && points.getName().equals("杆塔")) {
                    line.setType("架空线路");
                    line.setType_Id("11");
                } else {
                    line.setType("电缆");
                    line.setType_Id("42");
                }
                line.setBackNum("1");
                line.setStatue("新建");
                line.setNum("1");
                if (lineList.size() > 0) {
                    int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
                    if (line.getType().equals("架空线路"))
                        line.setName("架空线路-" + mad + "#");
                    else
                        line.setName("电缆-" + mad + "#");
                } else {
                    if (line.getType().equals("架空线路"))
                        line.setName("架空线路-" + 1 + "#");
                    else
                        line.setName("电缆-" + 1 + "#");
                }
                MyApplication.getInstances().getLineDao().insert(line);
                points.setDangju(lengths);
            }

        }

        return MyApplication.getInstances().getPointsDao().insert(points);
    }

}
